package demo.android.com.mvpdemo.OKHttp;


import android.util.Log;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import demo.android.com.mvpdemo.OKHttp.interceptor.BridgeInterceptor;
import demo.android.com.mvpdemo.OKHttp.interceptor.CallServerInterceptor;
import demo.android.com.mvpdemo.OKHttp.interceptor.Interceptor;
import demo.android.com.mvpdemo.OKHttp.interceptor.RealInterceptorChain;


/**
 * Created by Vya on 2018/1/18 0018.
 */

public class RealCall implements Call{
    private final Request orignalRequest;
    private final OkHttpClient client;
    public RealCall(Request request, OkHttpClient okHttpClient) {
        orignalRequest = request;
        client = okHttpClient;
    }

    public static Call newCall(Request request, OkHttpClient okHttpClient) {
        return new RealCall(request,okHttpClient);
    }

    @Override
    public void enqueue(Callback callback) {

        //异步操作
        AsyncCall asyncCall = new AsyncCall(callback);
        //交给线程池
        client.dispatcher.enqueue(asyncCall);
    }

    @Override
    public Response execute() {
        return null;
    }

    final class AsyncCall extends NamedRunnable {

        Callback callback;
        public AsyncCall(Callback callback){
            this.callback = callback;
        }
        @Override
        protected void execute() {
            //来到这里访问网络，把Request->变成Response
            Log.e("wangyan","AsyncCall--execute>>>");

            final Request request = orignalRequest;

            try {
                List<Interceptor> interceptors = new ArrayList<>();
                interceptors.add(new BridgeInterceptor());
                interceptors.add(new CallServerInterceptor());
                Interceptor.Chain chain = new RealInterceptorChain(interceptors,0,orignalRequest);
                Response response = chain.proceed(request);
                callback.onResponse(RealCall.this,response);

            }catch (IOException e){
                callback.onFailure(RealCall.this,e);
            }

        }
    }
}
